// 引入数据模型
const OrderModel = require("../model/orders.model");
const OrderDetailModel = require("../model/orderDetail.model");
const Goods = require("../model/goods.model");
const Cart = require("../model/cart.model");
// 创建订单类
class OrderService {
  // 创建订单
  async insertOrder({ userId, contactId, totalPrice, goodsList, orderStatus }) {
    // 创建主订单记录
    const order = await OrderModel.create({
      user_id: userId,
      contact_id: contactId,
      total_amount: totalPrice,
      order_state: orderStatus,
    });

    // 创建订单详情记录
    goodsList.forEach(async (item) => {
      // 查询商品信息
      const goods = await Goods.findOne({
        where: {
          product_id: item.productId,
        },
      });
      // 创建详情记录
      const details = await OrderDetailModel.create({
        order_id: order.order_id,
        product_id: item.productId,
        quantity: item.quantity,
        product_price: goods.dataValues.price,
        product_name: goods.dataValues.product_name,
        product_img: goods.dataValues.product_img,
      });
    });

    if (order) {
      // 删除购物车中的商品
      await Cart.destroy({
        where: {
          user_id: userId,
          // product_id: goodsList.map((item) => item.productId),
        },
      });
    }

    return order;
  }

  // 获取订单列表
  async gainOrderList({ userId, status }) {
    // 查询订单列表
    if (status === "0") {
      const orderList = await OrderModel.findAll({
        where: {
          user_id: userId,
        },
        include: {
          model: OrderDetailModel,
          // include: {
          //   model: Goods,
          // },
        },
      });
      return orderList;
    } else {
      const orderList = await OrderModel.findAll({
        where: {
          user_id: userId,
          order_state: status,
        },
      });

      return orderList;
    }
  }

  // 确认收货
  async updateOrderStatus({ orderId }) {
    const result = await OrderModel.update(
      {
        order_state: "1",
      },
      {
        where: {
          order_id: orderId,
        },
      }
    );
    return result;
  }
}

// 导出实例
module.exports = new OrderService();
